package test;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class Home03ServerA {

    ServerSocket serverSocket;
    public Home03ServerA(int port) throws Exception {
        serverSocket = new ServerSocket(port);//创建一个指定端口号
    }
    public void start() throws Exception {
        while(true) {
            Socket socket = serverSocket.accept();
            //查找包含该关键字的文件
            try (                BufferedReader bis = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                                 PrintWriter bos = new PrintWriter(socket.getOutputStream(), true);
//                    BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
//                 BufferedInputStream bis = new BufferedInputStream(socket.getInputStream())
            ) {
                //接受传过来的歌名,转化成字符串
//                String name = UtilAPi.streamToString(bis);
                String name=bis.readLine();
                System.out.println(name);
                List<File> array = searchMusic("D:\\music",name);
                if (!array.isEmpty()) {
                    for (File file : array) {
                        //返回文件名

                        if (file.isFile()) {
                            //用于标记是否结束
                            bos.write(1);
                            //如果是普通文件再进行下面的操作
                            //  bos.flush();
                            if (file.getName().equals(name)) {
//                                byte[] ArrayName = file.getName().getBytes(StandardCharsets.UTF_8);
//                                bos.write(ArrayName);
//                                // bos.flush();
//                                //如果名字一样就返回该文件
//                                byte[] b = UtilAPi.getByteArray(new FileInputStream(file));//获取二进制数组
//                                //将该文件返回
//                                bos.write(b);
//                                // bos.flush();
                                String filePath = "D:\\music\\" + name;  // 指定目录的路径
                                FileInputStream fileInputStream = new FileInputStream(new File(filePath));
                                OutputStream outputStream = socket.getOutputStream();
                                byte[] buffer = new byte[4096];
                                int bytesRead;
                                while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                                    outputStream.write(buffer, 0, bytesRead);
                                }
                            }
                        }
                    }
                }
                //如果返回的是-1就说明结束了
                bos.write(-1);
                //bos.flush();
                System.out.println(socket.getInetAddress().getHostName() + "/" + socket.getPort() + " 结束");
            }
        }
    }

    private static List<File> searchMusic(String directoryPath, String keyword) {
        List<File> musicFiles = new ArrayList<>();
        File directory = new File(directoryPath);

        if (directory.exists() && directory.isDirectory()) {
            searchMusicInDirectory(directory, keyword, musicFiles);
        }

        return musicFiles;
    }

    private static void searchMusicInDirectory(File directory, String keyword, List<File> musicFiles) {
        File[] files = directory.listFiles();

        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    searchMusicInDirectory(file, keyword, musicFiles);
                } else if (file.getName().toLowerCase().contains(keyword.toLowerCase())) {
                    musicFiles.add(file);
                }
            }
        }
    }

//    private ArrayList<File> lookUp(String request) {
//        //创建一个读取文件的流
//        //从这个目录中查找
//        File file = new File("D:\\music");
//        ArrayList<File> arrayList = new ArrayList<>();
//        if(file.isDirectory()){
//            //如果是目录就遍历这个目录里的所有文件名
//            File[] files = file.listFiles();
//            assert files != null;
//            for (File n:files) {
//               if(n.isFile()){
//                   //如果找到就加入这个数组
//                   //只要包含就加入
//                   if(n.getName().contains(request)){
//                       arrayList.add(n);
//                   }
//               }
//            }
//        }
//        return arrayList;
//    }

    /**
     * 读取文件,查找音乐,这个是服务器
     */

    public static void main(String[] args) throws Exception {
        Home03ServerA serverA = new Home03ServerA(9999);
        serverA.start();

    }
}
